<template>
    <div>
        <!-- 搜索栏和操作按钮栏 -->
        <div class="search-and-actions">
            <div class="search-container">
                <el-input style="width: 200px; margin-bottom: 10px;" suffix-icon="el-icon-search" :placeholder="$t('common.pleaseEnter') + ' ' + $t('user.name')" v-model="userName" />
                <el-input style="width: 200px; margin-bottom: 10px;" suffix-icon="el-icon-message" :placeholder="$t('common.pleaseEnter') + ' ' + $t('common.email')" class="m-2" v-model="userMail" />
                <el-input style="width: 200px; margin-bottom: 10px;" suffix-icon="el-icon-user" :placeholder="$t('common.pleaseEnter') + ' ' + $t('group.title')" class="m-2" v-model="userGroup" />
                <el-button class="m-2" type="primary" @click="loadData">{{ $t('common.search') }}</el-button>
            </div>
            <div class="actions-container">
                <el-button type="primary" plain @click="handleAdd" class="operation-button">
                    {{ $t('common.add') }} <i class="el-icon-circle-plus-outline"></i>
                </el-button>
                <el-upload 
                    style="display: inline-block" 
                    class="upload-demo ml-5 mr-5"
                    action="http://192.168.137.5:8088/user/import"
                    :show-file-list="false"
                    :on-success="handleUpSuccess"
                    :on-error="handleUpError"
                    multiple 
                    accept="xlsx"
                    :limit="1"
                >
                    <el-button type="primary" plain class="operation-button">{{ $t('common.import') }} <i class="el-icon-bottom"></i></el-button>
                </el-upload>
                <el-button type="primary" plain @click="exportExcel" class="operation-button export-button" :loading="exportLoading">
                    {{ $t('common.export') }} <i class="el-icon-top"></i>
                </el-button>
                <el-popconfirm :title="$t('common.deleteConfirm')" @confirm="handleDeleteBatch" class="ml-5">
                    <el-button type="danger" plain slot="reference" class="operation-button">{{ $t('common.delete') }} <i class="el-icon-remove-outline"></i></el-button>
                </el-popconfirm>
            </div>
        </div>

        <!-- 用户数据表格 -->
        <div class="table-container">
            <el-table 
                :data="tableData" 
                border 
                stripe
                :max-height="tableHeight"
                row-key="id"
                :header-cell-style="headClass"
                :cell-style="cellClass"
                @selection-change="handleSelectionChange"
                default-expand-all
            >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="id" label="ID" min-width="80"></el-table-column>
                <el-table-column prop="name" :label="$t('user.name')" min-width="100"></el-table-column>
                <el-table-column prop="telephone" :label="$t('common.telephone')" min-width="120"></el-table-column>
                <el-table-column prop="mail" :label="$t('common.email')" min-width="150"></el-table-column>
                <el-table-column prop="groupName" :label="$t('group.title')" min-width="100"></el-table-column>
                <el-table-column prop="roles" :label="$t('common.role')" min-width="150">
                    <template slot-scope="scope">
                        <template v-if="scope.row.roles && scope.row.roles.length > 0">
                            <el-tag v-for="roleId in scope.row.roles" :key="roleId" style="margin-right: 5px; margin-bottom: 5px;">
                                {{ rolesMap[roleId] || $t('role.unknown') }}
                            </el-tag>
                        </template>
                        <el-tag v-else type="info">{{ $t('role.none') }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="status" :label="$t('user.isDisabled')" min-width="100">
                    <template slot-scope="scope">
                        <el-tag :type="getUserStatusType(scope.row.status)">
                            {{ getUserStatusText(scope.row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="lastTime" :label="$t('user.lastLogin')" min-width="180"></el-table-column>
                <el-table-column prop="createTime" :label="$t('common.createdTime')" min-width="180"></el-table-column>
                <el-table-column prop="option" :label="$t('common.operation')" min-width="280" fixed="right" v-if="!isMobile">
                    <template slot-scope="scope">
                        <div class="operation-buttons">
                            <el-button type="primary" size="mini" @click="handleMenu(scope.row)">
                                <i class="el-icon-menu"></i> {{ $t('user.roleSettings') }}
                            </el-button>
                            <el-button type="warning" size="mini" @click="handleEdit(scope.$index, scope.row)">
                                <i class="el-icon-edit"></i> {{ $t('common.edit') }}
                            </el-button>
                            <el-popconfirm :title="$t('common.deleteConfirm')" @confirm="handleDelete(scope.$index, scope.row)">
                                <el-button type="danger" size="mini" slot="reference">
                                    <i class="el-icon-remove-outline"></i> {{ $t('common.delete') }}
                                </el-button>
                            </el-popconfirm>
                        </div>
                    </template>
                </el-table-column>
                
                <!-- 移动端操作列 -->
                <el-table-column prop="option" :label="$t('common.operation')" width="100"  fixed="right" v-if="isMobile">
                    <template slot-scope="scope">
                        <el-popover
                            placement="left"
                            width="160"
                            trigger="click">
                            <div class="mobile-operation-buttons">
                                <el-button 
                                    type="text" 
                                    size="mini" 
                                    @click="handleMenu(scope.row)">
                                    <i class="el-icon-menu"></i> {{ $t('user.roleSettings') }}
                                </el-button>
                                <el-button 
                                    type="text" 
                                    size="mini" 
                                    @click="handleEdit(scope.$index, scope.row)">
                                    <i class="el-icon-edit"></i> {{ $t('common.edit') }}
                                </el-button>
                                <el-popconfirm :title="$t('common.deleteConfirm')" @confirm="handleDelete(scope.$index, scope.row)">
                                    <el-button 
                                        type="text" 
                                        size="mini" 
                                        slot="reference"
                                        class="delete-button">
                                        <i class="el-icon-remove-outline"></i> {{ $t('common.delete') }}
                                    </el-button>
                                </el-popconfirm>
                            </div>
                            <el-button slot="reference" type="primary" size="mini">
                                {{ $t('common.operation') }} <i class="el-icon-arrow-down"></i>
                            </el-button>
                        </el-popover>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页器 -->
        <div class="pagination-container">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 30, 50]"
                :page-size="pageSize"
                :layout="paginationLayout"
                :total="total">
            </el-pagination>
        </div>

        <!-- 用户信息编辑弹窗 -->
        <el-dialog :title="$t('user.info')" :visible.sync="dialogFormVisible" width="90%" :fullscreen="isMobile">
            <el-form :model="form" :inline="!isMobile" label-position="left">
                <el-form-item :label="$t('user.name')">
                    <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item :label="$t('user.password')" v-show="isEditPassword">
                    <el-input v-model="form.password" v-show="isEditPassword" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item :label="$t('common.telephone')">
                    <el-input v-model="form.telephone" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item :label="$t('common.email')">
                    <el-input v-model="form.mail" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item :label="$t('group.title')">
                    <el-select v-model="form.groupId">
                        <el-option 
                            v-for="group in groupOptions"
                            :key="group.id"
                            :label="group.name"
                            :value="group.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('common.status')">
                    <el-select v-model="form.status">
                        <el-option :label="$t('common.enabled')" :value="1"></el-option>
                        <el-option :label="$t('common.disabled')" :value="0"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">{{ $t('common.cancel') }}</el-button>
                <el-button type="primary" @click="save">{{ $t('common.confirm') }}</el-button>
            </div>
        </el-dialog>

        <!-- 角色设置弹窗 -->
        <el-dialog :title="$t('user.roleSettings')" :visible.sync="dialogMenuVisible" width="90%" :fullscreen="isMobile">
            <el-form :model="form" :inline="!isMobile">
                <el-form-item :label="$t('common.role')">
                    <el-select v-model="roleId" 
                     :placeholder="$t('common.pleaseSelect')" >
                        <el-option
                            v-for="item in role"
                            :key="item.id"
                            :value="item.id"
                            :label="item.name">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogMenuVisible = false">{{ $t('common.cancel') }}</el-button>
                <el-button type="primary" @click="handleRole">{{ $t('common.confirm') }}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import ElementUI from "element-ui";
import { exportFile } from '@/utils/exportHelper';

export default {
    name: "UserManage",
    data() {
        return {
            userInfo: JSON.parse(sessionStorage.getItem("userInfo") || "{}"),
            dialogFormVisible: false,
            dialogMenuVisible: false,
            form: {},
            isEditPassword: true,
            isGroupShow: "none",

            tableData: [],
            pageSize: 9, //每页的数据条数
            currentPage: 1, //默认开始页面
            total: 0, //总条数
            multipleSelection: [],

            userName: "",
            userMail: "",
            userGroup: "",
            rawId: [],
            isPower: false,
            isMobile: window.innerWidth < 768, // 判断是否为移动设备
            exportLoading: false, // 添加导出状态标识

            // 角色相关
            rolesMap: {}, 
            role: [],
            roleId: "",
            userId: "",

            // 用户状态映射（根据SQL字段定义）
            userStatusMap: {
                0: { text: 'common.disabled', type: 'danger' },  // 冻结
                1: { text: 'common.enabled', type: 'success' },  // 正常
                2: { text: 'common.deleted', type: 'info' }      // 删除
            },

            // 班级选项
            groupOptions: [
                { id: 0, name: this.$t('group.unassigned') },
                { id: 1, name: this.$t('group.name') + '1' },
                { id: 2, name: this.$t('group.name') + '2' }
            ],
            groupsMap: {},
            
            // 响应式设计相关
            tableHeight: 650,
            paginationLayout: "total, sizes, prev, pager, next, jumper",
            screenWidth: document.body.clientWidth
        }
    },

    created() {
        this.loadData()
        this.loadRoles()
        this.initGroupsMap()
        this.checkScreenSize()
    },
    
    mounted() {
        window.addEventListener('resize', this.checkScreenSize)
        this.checkScreenSize()
    },
    
    beforeDestroy() {
        window.removeEventListener('resize', this.checkScreenSize)
    },

    methods: {
        // 获取用户状态显示文本
        getUserStatusText(status) {
            const statusInfo = this.userStatusMap[status] || { text: 'common.unknown' };
            return this.$t(statusInfo.text);
        },

        // 获取用户状态标签类型
        getUserStatusType(status) {
            return (this.userStatusMap[status] || { type: 'info' }).type;
        },

        // 检查屏幕尺寸并设置相应的布局
        checkScreenSize() {
            this.screenWidth = document.body.clientWidth
            this.isMobile = this.screenWidth < 768
            
            // 根据屏幕尺寸调整分页控件布局
            if (this.isMobile) {
                this.paginationLayout = "prev, pager, next"
                this.tableHeight = 450
            } else {
                this.paginationLayout = "total, sizes, prev, pager, next, jumper"
                this.tableHeight = 650
            }
        },
        
        // 初始化班级映射
        initGroupsMap() {
            this.groupsMap = this.groupOptions.reduce((map, group) => {
                map[group.id] = group.name;
                return map;
            }, {});
        },

        // 加载角色数据
        loadRoles() {
            this.$axios.get('/role/all').then(res => {
                if (res.code === 200) {
                    const roles = res.data || [];
                    this.role = roles;
                    this.rolesMap = roles.reduce((map, role) => {
                        map[role.id] = role.name;
                        return map;
                    }, {});
                } else {
                    this.$message.error('获取角色列表失败');
                }
            }).catch(error => {
                console.error('获取角色列表失败:', error);
                this.$message.error('获取角色列表失败');
            });
        },

        handleMenu(row) {
            this.dialogMenuVisible = true;
            this.userId = row.id;
            
            if (this.role && this.role.length > 0) return;
            
            this.$axios.get("/role/all").then(res => {
                if (res.code === 200) {
                    this.role = res.data || [];
                } else {
                    this.$message.error(this.$t('common.operationFailed'));
                }
            }).catch(error => {
                console.error(this.$t('common.operationFailed'), error);
                this.$message.error(this.$t('common.operationFailed'));
            });
        },

        handleRole() {
            const role = {
                userId: this.userId,
                roleId: this.roleId
            };
            
            this.$axios.post("/userRole/setRole", role).then(res => {
                if (res.code === 200) {
                    ElementUI.Message.success(this.$t('common.operationSuccess'));
                    this.dialogMenuVisible = false;
                    this.loadData();
                }
            });
        },

        // 表格样式
        headClass() {
            return 'background:#E6F1FF;color:#368CFF;font-size:13px;text-align: center;'
        },

        cellClass() {
            return 'text-align: center;'
        },

        // 分页方法
        handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.loadData();
        },

        handleCurrentChange(currentPage) {
            this.currentPage = currentPage;
            this.loadData();
        },

        // 用户操作方法
        handleAdd() {
            this.dialogFormVisible = true;
            this.form = {};
            this.isEditPassword = true;
        },

        save() {
            this.$axios.post("/user/add", this.form).then(res => {
                if (res.code === 200) {
                    ElementUI.Message.success(this.$t('common.operationSuccess'));
                    this.dialogFormVisible = false;
                    this.isEditPassword = true;
                    this.loadData();
                }
            });
        },

        handleEdit(index, row) {
            this.isEditPassword = false;
            this.dialogFormVisible = true;
            this.form = row;
        },

        handleDelete(index, row) {
            this.$axios.delete("/user/delete/" + row.id).then(res => {
                if (res.code === 200) {
                    ElementUI.Message.success(this.$t('common.operationSuccess'));
                    this.loadData();
                }
            });
        },

        handleDeleteBatch() {
            this.$axios.post("/user/delete/batch/", this.rawId).then(res => {
                if (res.code === 200) {
                    ElementUI.Message.success(this.$t('common.operationSuccess'));
                    this.loadData();
                }
            });
        },

        handleSelectionChange(raw) {
            this.rawId = raw.map(item => item.id);
        },

        // 导入导出方法
        exportExcel() {
            exportFile({
                url: '/user/export',
                defaultFileName: this.$t('user.title'),
                beforeExport: () => {
                    this.exportLoading = true;
                },
                afterExport: () => {
                    this.exportLoading = false;
                },
                onError: (error) => {
                    console.error(this.$t('common.operationFailed'), error);
                },
                fileType: 'csv',
                getCustomFileName: () => {
                    // 生成自定义文件名
                    const now = new Date();
                    const dateStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
                    let fileName = `${this.$t('user.title')}_${dateStr}`;
                    
                    // 如果有搜索条件，添加到文件名中
                    if (this.userName) fileName += `_${this.userName}`;
                    if (this.userGroup) fileName += `_${this.userGroup}`;
                    
                    return fileName;
                }
            });
        },

        handleUpSuccess() {
            ElementUI.Message.success(this.$t('common.operationSuccess'));
            this.loadData();
        },

        handleUpError() {
            ElementUI.Message.error(this.$t('common.operationFailed'));
            this.loadData();
        },

        // 数据加载方法
        loadData() {
            this.$axios.get("/user/list", {
                params: {
                    currentPage: this.currentPage,
                    pageSize: this.pageSize,
                    userName: this.userName,
                    userMail: this.userMail,
                    userGroup: this.userGroup
                }
            }).then(res => {
                if (res.code === 200) {
                    this.tableData = res.data.records;
                    this.total = res.data.total;

                    // 为每个用户添加角色和班级信息
                    this.tableData.forEach(user => {
                        // 初始化角色数组
                        if (!user.roles) {
                            this.$set(user, 'roles', []);
                        }

                        // 设置班级名称
                        user.groupName = this.groupsMap[user.groupId] || this.$t('group.unassigned');
                        
                        // 获取用户角色
                        this.getUserRoles(user.id, user);
                    });
                } else {
                    this.$message.error(this.$t('common.operationFailed'));
                }
            }).catch(error => {
                console.error(this.$t('common.operationFailed'), error);
                this.$message.error(this.$t('common.operationFailed'));
            });
        },
        
        // 获取用户角色
        getUserRoles(userId, user) {
            this.$axios.get(`/userRole/getUserRoles/${userId}`).then(res => {
                if (res.code === 200 && res.data) {
                    // 将返回的角色ID数组赋值给用户的roles属性
                    this.$set(user, 'roles', res.data);
                }
            }).catch(error => {
                console.error('获取用户角色失败:', error);
            });
        },
    }
};
</script>

<style scoped>
/* 样式美化 */
.el-button {
    transition: background-color 0.3s;
}

.el-button:hover {
    background-color: #409EFF;
    color: white;
}

.el-table th, .el-table td {
    text-align: center;
}

.upload-demo {
    margin-left: 10px;
    margin-right: 10px;
}

.table-container {
    width: 100%;
    overflow-x: auto;
}

.pagination-container {
    padding: 10px 0;
    display: flex;
    justify-content: center;
}

.operation-buttons {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 5px;
}

.operation-button {
    margin-bottom: 5px;
    margin-right: 5px;
}

.search-and-actions {
    margin: 10px;
}

@media screen and (max-width: 768px) {
    .search-and-actions {
        flex-direction: column;
    }
    
    .search-container, .actions-container {
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 10px;
    }
    
    .el-table {
        width: 100%;
        font-size: 12px;
    }
    
    .el-button {
        padding: 7px 10px;
        font-size: 12px;
    }
    
    .el-input {
        width: 100%;
        margin-bottom: 10px;
    }
    
    .el-select {
        width: 100%;
    }
}

@media screen and (min-width: 769px) {
    .search-and-actions {
        display: flex;
        justify-content: space-between;
    }
}

.mobile-operation-buttons {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.mobile-operation-buttons .el-button {
    margin-left: 0;
    margin-bottom: 8px;
    width: 100%;
    text-align: left;
}

.mobile-operation-buttons .el-button:last-child {
    margin-bottom: 0;
}

.mobile-operation-buttons .delete-button {
    color: #F56C6C;
}
</style>